package com.learn.security.modules.sms;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lee
 */
@Slf4j
public class SmsUtil {

    private static final String REGION_ID = "cn-chengdu";
    private static final String ACCESS_KEY_ID = "xxx";
    private static final String SECRET = "xxx";
    private static final String SYS_DOMAIN = "dysmsapi.aliyuncs.com";
    private static final String SIGN_NAME = "xxx";
    private static final String SYS_VERSION = "2017-05-25";

    private static final DefaultProfile profile = DefaultProfile.getProfile(REGION_ID, ACCESS_KEY_ID, SECRET);
    private static final IAcsClient client = new DefaultAcsClient(profile);


    /**
     * 发送短信验证码
     *
     * @param mobile 电话
     * @return
     * @author Lee
     * @date 2020-09-01 15:58:49
     */
    public static CommonResponse sendSms(String mobile) {
        return sendSms(mobile, RandomUtil.randomInt(1000, 9999) + "");
    }

    /**
     * 发送短信验证码
     * 单条短信
     *
     * @param mobile 电话
     * @param code   验证码
     * @return
     * @author Lee
     * @date 2020-09-01 15:58:59
     */
    @SneakyThrows
    public static CommonResponse sendSms(String mobile, String code) {
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(SYS_DOMAIN);
        request.setSysVersion(SYS_VERSION);
        request.setSysAction(SmsActionEnum.SIMPLE.getAction());
        request.putQueryParameter("RegionId", REGION_ID);
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", SIGN_NAME);
        request.putQueryParameter("TemplateCode", SmsTempEnum.SMS_177553329.getCode());
        request.putQueryParameter("TemplateParam", getCodeJson(code));
        return client.getCommonResponse(request);
    }

    /**
     * code json格式化
     *
     * @param code 验证码
     * @return
     */
    private static String getCodeJson(String code) {
        JSONObject obj = JSONUtil.createObj();
        return obj.set("code", code).toString();
    }

    public static void main(String[] args) {
        CommonResponse resp = sendSms("18215628861");
        System.err.println(resp.getData());
    }
}
